#!/usr/bin/node

const http = require('http'),
      fs = require('fs'),
      qs = require('querystring'),
      log = console.log;


let items = [],
    result={
      status:200,
      reason:'ok',
      data:[],
      conut:0

    } 

http.createServer((req, res) => {
      logRequest(req);
      if (req.url.slice(0, 5) !== '/todo') {
          res.end('not api');              
      }
      switch (req.method) {
         case 'GET':
              select(req, res);
              break;
        case 'POST':
              insert(req, res)
              break;
        case 'PUT':
            update(req, res);
             break;
        case 'DELETE':
            remove(req,res);
            break;
        default:
          res.end('cuole');                                                              
      }


}).listen(8080);
function select (req,res){
      result.data = items;
          res.end(JSON.stringify(result));

}
function insert (req,res){
      let data = '';
          req.on('data',chunk => data+=chunk);
          req.on('end',()=>{
              let item = qs.parse(data).item;
               if(item!=='' && typeof item !== undefined){
                  items.push(item);
                  res.end(JSON.stringify(result));    
              }
              else{
                  result.status=401;
                  result.reason='item is empty';
                  res.end(JSON.stringify(result));                                                                    }
          })

}
function update (req,res){
      let id =req.url.split(':')[1];
      let data ='' ;
          req.on('data',chunk =>data+=chunk);
          req.on('end',()=>{
          let item = qs.parse(data).item;
          if(item !== '' && typeof item!==undefined){
                items[id] = item;
                res.end(JSON.stringify(result))                        
          }
          else{
                result.status=402
                result.reason='错误 '
                res.end(JSON.stringify(result));                         
          }
          })
      let item = items[id];
      res.end(req.method);
}
function remove (req,res){
      res.end(req.method);

}
function logRequest(req) {
    log(`${req.method}`);
    log(req.url);
    log(req.httpVersion);
}
